package cn.tedu.service.impl;

import cn.tedu.annotation.CacheExpire;
import cn.tedu.mapper.ItemMapper;
import cn.tedu.pojo.Item;
import cn.tedu.service.ItemService;
import cn.tedu.vo.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper,Item> implements ItemService {


    @Autowired
    private ItemMapper itemMapper;

    /**
     * 此业务不合理.如果item有其他的会走缓存, 仅作学习, 改善方法 item对象变成String cid
     * 通过分类来缓存分页即可
     * @param item
     * @param pageSize
     * @param currentSize
     * @return
     */
    @CacheExpire(expire = 300)
    @Cacheable(value = {"item"},key="#root.methodName+'_'+#item.getCid()+'_'+#pageSize+'_'+#currentSize")
   // @Cacheable(value = {"item"},keyGenerator = "keyGenerator")
    @Override
    public PageInfo<Item> pageList(Item item,String pageSize,String currentSize) {

        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isAllEmpty(item.getTitle()),"title",item.getTitle())
                .like(!StringUtils.isAllEmpty(item.getSellPoint()),"sell_point",item.getSellPoint());

        IPage<Item> page = new Page<Item>(Long.parseLong(currentSize), Long.parseLong(pageSize));
        itemMapper.selectPage(page, queryWrapper);

        PageInfo<Item> pageInfos = new PageInfo<>();
        pageInfos.setCurrent(Integer.parseInt(currentSize));
        pageInfos.setSize(Integer.parseInt(pageSize));
        pageInfos.setList(page.getRecords());
        pageInfos.setTotal(page.getTotal());
        return pageInfos;
    }

    @CacheExpire(expire = 300)
    @Cacheable(value = {"item"},key="#root.args[0]",sync = false)
    @Override
    public Item findItemById(String id) {


        //try {
        //    Thread.sleep(100000);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}
        return itemMapper.selectById(id);
    }

    @CacheExpire(expire = 300)
    @CachePut(value = {"item"},key="#root.args[0].id")
    @Override
    public Item updateItemById(Item item) {
        System.out.println(item);
        itemMapper.updateById(item);
        return item;
    }


    @CacheEvict(value={"item"},key="#root.args[0]")
    @Override
    public void removeItemById(String id) {
        itemMapper.deleteById(id);
    }
}
